import 'dart:convert';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import '../../../../base/base_state.dart';
import '../../../../bean/user.dart';
import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_constant.dart';
import '../../../../utils/router_helper.dart';
import '../../../../utils/common_req_utils.dart';
import '../../../../widget/common_dialog.dart';
import '../../../../widget/label_item.dart';
import '../../../../widget/w_popup_window.dart';
import '../../../../widget/w_toast.dart';
import '../../model/book_manage_model.dart';

class BookAddPage extends StatefulWidget {
  const BookAddPage({super.key});

  @override
  BaseState<BookAddPage> createState() => _BookAddPageState();
}

class _BookAddPageState extends BaseState<BookAddPage> {
  final _formKey = GlobalKey<FormState>();
  List<Map> modelList =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.carType);
  List<Map> appointType =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.appointType);

  List<Map> saleManList = WConstant().salesmanList;

  //初始化试驾预约登记对象
  Map bookInfo = {
    "customerName": "",
    "phone": "",
    "appointType": "",
    "modelId": "",
    "saleMan": "",
    "arriveDate": "",
    "appointTime": "",
    "remark": "",
  };

  //是否是销售顾问, 或者店长
  bool isAdviser = false;
  String saleMan = "";

  List? timeSlots = [];
  List? filterTimeSlots = [];

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "新增邀约",
        resizeToBottomInset: true,
        child: Column(children: [
          Expanded(
            child: SingleChildScrollView(
                padding: EdgeInsets.zero, child: _bookDriveItem(context, 0)),
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.px, vertical: 10.px),
            child: GestureDetector(
              onTap: () {
                if (!BookManageModel.check(bookInfo)) {
                  return;
                }
                CommonUtils.throttle(addBook);
              },
              child: Container(
                margin:
                    EdgeInsets.symmetric(vertical: 16.px, horizontal: 10.px),
                width: SizeUtils.screenW() - 48.px,
                alignment: Alignment.center,
                height: 48.px,
                decoration: BoxDecoration(
                  color: WColors.primaryColor,
                  borderRadius: BorderRadius.circular(24.px),
                ),
                child: WText(
                  "提交",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: WDimens.tsXLarge,
                  ),
                ),
              ),
            ),
          ),
        ]));
  }

  void addBook() {

    //如果是试驾类型，校验车型必填
    if (bookInfo["appointType"] == "10221002") {
      if (bookInfo["modelId"] == "") {
        Toast.toast("试驾类型，车型必填");
        return;
      }
    }
    showLoading();
    HttpUtils().post(Api.saveTestDriveBookingInfo, data: bookInfo).then((data) {
      hideLoading();
      if (data.resultCode == 200) {
        Toast.toast("预约新增成功");
        RouteHelper.maybePop(context, true);
      } else {
        Toast.toast(data.errMsg ?? "");
      }
    }).catchError((e) {
      hideLoading();
    });
  }

  Widget _bookDriveItem(context, index) {
    return Form(
        key: _formKey,
        child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(
                left: 16.px, right: 16.px, bottom: 10.px, top: 10.px),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.px),
                color: Colors.white,
                boxShadow: const [
                  BoxShadow(
                      //线框阴影线条
                      color: WColors.CDFEFFB,
                      offset: Offset(0, 1),
                      blurRadius: 3)
                ]),
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  LabelItem(
                    labelType: LabelType.INPUT,
                    label: "客户名称",
                    maxLength: 50,
                    isMust: true,
                    onChanged: (text) {
                      setState(() {
                        bookInfo["customerName"] = text;
                      });
                    },
                  ),
                  LabelItem(
                    labelType: LabelType.INPUT,
                    // textInputType: TextInputType.number,
                    label: "手机号码",
                    maxLength: 11,
                    isMust: true,
                    onChanged: (text) {
                      setState(() {
                        bookInfo["phone"] = text;
                      });
                    },
                  ),
                  LabelItem(
                    label: "预约类型",
                    isMust: true,
                    labelType: LabelType.LIST,
                    onSelected: (index) {
                      setState(() {
                        bookInfo["appointType"] = index;
                      });
                    },
                    dataList: appointType,
                  ),
                  LabelItem(
                    label: "车型",
                    labelType: LabelType.DROW_DOWN,
                    // isMust: true,
                    isModel: true,
                    onSelected: (index) {
                      setState(() {
                        bookInfo["modelId"] = index;
                      });
                    },
                    dataList: modelList,
                  ),
                  isAdviser
                      ? LabelItem(
                          labelType: LabelType.DROW_DOWN,
                          label: "接待顾问",
                          isMust: true,
                          isModel: true,
                          onSelected: (index) {
                            setState(() {
                              bookInfo["saleMan"] = index;
                            });
                          },
                          dataList: saleManList,
                        )
                      : LabelItem(
                          label: "接待顾问",
                          isMust: true,
                          value: saleMan,
                        ),
                  LabelItem(
                    label: "到店日期",
                    isMust: true,
                    labelType: LabelType.DATE,
                    minDateTime: DateTime.now(),
                    selectedDate:
                        StringUtils.safeGetValue(bookInfo["arriveDate"]),
                    onDateChanged: (date) {
                      filterTimeSlot(date);
                      bookInfo["arriveDate"] = "$date 00:00:00";
                      bookInfo["appointTime"]="";
                      setState(() {});
                    },
                  ),
                  LabelItem(
                    label: "到店时间",
                    isMust: true,
                    labelType: LabelType.SELECT,
                    value: StringUtils.safeGetValue(bookInfo["appointTime"]),
                    onTap: (){
                      if(bookInfo["arriveDate"]==""){
                        Toast.toast("请先选择到店日期");
                        return ;
                      }
                      WPopupWindow.showBooKTime(dataList: filterTimeSlots??[],
                          context: context, bookInfo: bookInfo,onSelected: (info){
                        bookInfo = info;
                        setState(() {
                        });
                      });
                    },
                  ),
                  LabelItem(
                    labelType: LabelType.TEXTAREA,
                    label: "备注",
                    isLast: true,
                    maxTextLength: 500,
                    onChanged: (text) {
                      setState(() {
                        bookInfo["remark"] = text;
                      });
                    },
                  ),
                ])));
  }

  // 显示底部弹窗的方法


  String getSelectedTime(dataList) {
    String selectedTime = "";
    if (bookInfo["appointTime"] != null) {
      for (var slot in dataList) {
        if (slot["timeRange"] == bookInfo["appointTime"]) {
          selectedTime = slot["timeRange"];
          break;
        }
      }
    }
    return selectedTime;
  }

  void _printFormData() {
    //通过index获取code
    print("登记的对象是：$bookInfo");
  }

  void filterTimeSlot(String dateStr) {
    filterTimeSlots = [];
    DateTime selectDate = DateTime.parse(dateStr);
    DateTime today = DateTime.now();
    if (DateUtils.isSameDay(selectDate, today)) {
      for (int i = 0; i < timeSlots!.length; i++) {
        String endTimeStr = timeSlots![i]["timeRange"].split("-").last.trim();
        String temp = "$dateStr $endTimeStr:00";
        DateTime givenDate = DateTime.parse(temp);
        if (givenDate.isAfter(today)) {
          filterTimeSlots?.add(timeSlots![i]);
        }
      }
    } else {
      filterTimeSlots = timeSlots;
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    User user = WConstant().userInfo;
    isAdviser = user.roleCode == "DZ";
    saleMan = user.employeeName ?? "";
    if (!isAdviser) {
      bookInfo["saleMan"] = user.userId;
    }
    bookInfo["shopId"] = user.shopId;

    ///新增预约的时候加载排版数据
    HttpUtils().get("${Api.getTestDriveTimeList}/${user.shopId}").then((data) {
      hideLoading();
      if (data.resultCode == 200) {
        timeSlots = data.data;
        setState(() {});
      }
    }).catchError((e) {
      hideLoading();
    });
  }
}
